package com.example.sys.ai.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.core.utils.Base64Util;
import com.example.core.utils.StringUtils;
import com.example.sys.ai.dto.BankCard;
import com.example.sys.ai.dto.BusinessLicense;
import com.example.sys.ai.dto.Face;
import com.example.sys.ai.dto.IDCard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/***
 * baidu的AIP接口
 */
public class SysBaiDuAiHandler extends AbstractSysAiHandler {

    Logger logger = LoggerFactory.getLogger(getClass());

    private String appId;

    private String apiKey;

    private String secretKey;

    public String getApiKey() {
        if (StringUtils.isEmpty(this.apiKey)) {
            this.apiKey = getApplicationContext().getEnvironment().getProperty("ai.baidu.apiKey");
        }
        return apiKey;
    }

    public String getSecretKey() {
        if (StringUtils.isEmpty(this.secretKey)) {
            this.secretKey = getApplicationContext().getEnvironment().getProperty("ai.baidu.secretKey");
        }
        return secretKey;
    }

    public String getAppId() {
        if (StringUtils.isEmpty(this.appId)) {
            this.appId = getApplicationContext().getEnvironment().getProperty("ai.baidu.appId");
        }
        return appId;
    }

    /***
     * 获取API TOKEN信息
     * @return
     */
    @Override
    public String getToken() {
        if (!getRedisTemplate().hasKey(AI_TOKEN)) {
            String url = "https://aip.baidubce.com/oauth/2.0/token?" + "grant_type=client_credentials" + "&client_id=" + this.getApiKey() + "&client_secret=" + this.getSecretKey();
            JSONObject result = JSONObject.parseObject(HttpUtil.get(url));
            if (result.containsKey(TOKEN_KEY) && result.containsKey(EXPIRES_IN)) {
                getRedisTemplate().opsForValue().set(AI_TOKEN, result.getString(TOKEN_KEY), result.getLong(EXPIRES_IN), TimeUnit.SECONDS);
            }
        }
        return getRedisTemplate().opsForValue().get(AI_TOKEN);
    }

    /***
     * 身份证正面识别
     * @param imgData
     * @return
     * @throws Exception
     */
    @Override
    public IDCard.Front idCardFront(byte[] imgData) throws Exception {
        SysBaiDuAiHandler sysBaiDuAiHandler = new SysBaiDuAiHandler();
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        String param = "id_card_side=front&image=" + imgParam;
        String rtn = com.example.core.utils.HttpUtil.post(url, sysBaiDuAiHandler.getToken(), param);
        return new IDCard().toFront(rtn);
    }

    /***
     * 身份证反面
     * @param imgData
     * @return
     * @throws Exception
     */
    @Override
    public IDCard.Back idCardBack(byte[] imgData) throws Exception {
        SysBaiDuAiHandler sysBaiDuAiHandler = new SysBaiDuAiHandler();
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        String param = "id_card_side=back&image=" + imgParam;
        String rtn = com.example.core.utils.HttpUtil.post(url, sysBaiDuAiHandler.getToken(), param);
        return new IDCard().toBack(rtn);
    }


    /***
     * 银行卡号识别
     * @param imgData
     * @return
     * @throws Exception
     */
    @Override
    public BankCard bankCard(byte[] imgData) throws Exception {
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard";
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        String param = "image=" + imgParam;
        String rtn = com.example.core.utils.HttpUtil.post(url, getToken(), param);
        return BankCard.toCard(rtn);
    }

    /***
     * 识别营业执照
     * @param imgData
     * @return
     * @throws Exception
     */
    @Override
    public BusinessLicense businessLicense(byte[] imgData) throws Exception {
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license";
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        String param = "image=" + imgParam;
        String rtn = com.example.core.utils.HttpUtil.post(url, getToken(), param);
        return BusinessLicense.toLicense(rtn);
    }


    /***
     * 人脸识别返回匹配的分数
     * @param imgData 图片
     * @param name 姓名
     * @param code 身份证号
     * @return
     * @throws Exception
     */
    @Override
    public Face face(byte[] imgData, String name, String code) throws Exception {
        SysBaiDuAiHandler sysBaiDuAiHandler = new SysBaiDuAiHandler();
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/person/verify";
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        String param = "image=" + imgParam + "&name=" + URLEncoder.encode(name, "UTF-8") + "&id_card_number=" + code + "&image_type=" + "BASE64";
        String rtn = com.example.core.utils.HttpUtil.post(url, sysBaiDuAiHandler.getToken(), param);
        return Face.toFace(rtn);
    }
}
